'use strict';

const { Controller } = require('egg');
const fs = require('fs')
const path = require('path')
// 用户列表
const userList = [{
	id: 1,
	username: 'admin',
	password: 'admin',
	nickname: '管理员',
	avator: 'https://robohash.org/1231231231'
}, {
	id: 2,
	username: 'zhangsan',
	password: 'zhangsan',
	nickname: '张三',
	avator: 'https://robohash.org/1231231231123123132'
}]

class HomeController extends Controller {
	// 登录
	async signin() {
		// 获取ctx
		const { ctx } = this;
		// 获取请求数据
		const { username, password } = ctx.request.body;
		// 账户密码是否同时存在
		const user = userList.find(v => v.username === username && v.password === password)
		// 返回信息
		if (user) {
			ctx.body = {
				code: 200,
				message: '登录成功， 欢迎' + user.nickname,
				data: {
					nickname: user.nickname,
					avator: user.avator,
					id: user.id,
					username: user.username
				}
			};
		} else {
			ctx.body = {
				code: 401,
				message: '登录失败， 请重新登录',
				data: null
			};
		}

	}

	async upload() {
		const { ctx } = this;
		// 获取文件信息
		const file = ctx.request.files[0]
		// 获取文件保存的路径
		const filepath = file.filepath
		// 获取文件名字
		const filename = file.filename
		// 我们将将文件保存的位置
		const staticDir = path.resolve(__dirname, '../static', filename);
		// 复制文件
		await fs.promises.copyFile(filepath, staticDir)
		// 返回结果
		ctx.body = {
			code: 200,
			url: `http://localhost:7001/static/${filename}`
		}
	}
}

module.exports = HomeController;
